package com.grf.sse.service;

import com.grf.sse.utils.SseEmitterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

/**
 * @description:
 * @author: guorf
 * @date: 2024/8/7
 */
@Slf4j
@Service
public class SseService {

    /**
     * @description: 测试
     * @author: guorf
     * @date: 2024/8/7
     */
    public SseEmitter test(){
        SseEmitter emitter = new SseEmitter();
        for(int i=0; i<5; i++){
            try {
                String message = "消息 " + i+1;
                emitter.send(message);
                Thread.sleep(10000);
            } catch (Exception e) {
                log.warn("捕获异常：{}", e.getMessage());
                emitter.completeWithError(e);
            }
        }
        // 线程处理
        // new Thread(()->{
        //     while (true){
        //         try {
        //             String message = "消息 " + counter.incrementAndGet();
        //             emitter.send(message);
        //
        //             // SseEmitter.SseEventBuilder event = SseEmitter.event()
        //             //         .data(message)
        //             //         .name("customEvent");
        //             // emitter.send(event);
        //             Thread.sleep(10000);
        //         } catch (Exception e) {
        //             log.warn("捕获异常：{}", e.getMessage());
        //             emitter.completeWithError(e);
        //         }
        //     }
        // }).start();
        // complete() 示例
        emitter.onCompletion(() -> log.info("SSE Connection Close"));

        // onTimeout(Runnable callback) 示例
        emitter.onTimeout(() -> {
            log.warn("连接超时");
            // 释放资源
            emitter.complete();
        });

        // onError(ErrorCallback callback) 示例
        emitter.onError((Throwable t) -> log.warn("发生错误: {}" , t.getMessage()));
        return emitter;
    }

    /**
     * @description: 建立连接
     * @author: guorf
     * @date: 2024/8/7
     */
    public SseEmitter connect(String userId){
        return SseEmitterUtil.connect(userId);
    }

    /**
     * @description: 发送消息给指定用户
     * @author: guorf
     * @date: 2024/8/7
     */
    public void sendMessage(String userId, String message){
        SseEmitterUtil.sendMessage(userId, message);
    }
    /**
     * @description: 群发所有人
     * @author: guorf
     * @date: 2024/8/7
     */
    public void batchSendMessage(String message){
        int count = SseEmitterUtil.getUserCount();
        if (count > 0){
            SseEmitterUtil.batchSendMessage(message);
        } else {
            log.warn("当前没有用户在线");
        }

    }
    /**
     * @description: 群发消息-指定用户群
     * @author: guorf
     * @date: 2024/8/7
     */
    public void batchSendMessage(List<String> ids, String message) {
        SseEmitterUtil.batchSendMessage(ids, message);
    }

    /**
     * @description: 关闭连接
     * @author: guorf
     * @date: 2024/8/7
     */
    public void closeConnect(String userId){
        SseEmitterUtil.removeUser(userId);
        log.info("用户【{}】断开连接", userId);
    }
}
